const app = getApp();
import areaList from "../../utils/area.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    theme:app.theme,
    noticeText:'嫌麻烦，试试一键获取微信地址',
    show: false,
    areaList,
    delivery_name: '',
    mobile: '',
    province: '',
    city: '',
    district: '',
    area_code: '',
    address: '',
    is_default: 0,
    values:[],
    xiaoqu:"",//通过小程序地图获取的位置信息
    lng:"",
    lat:'',
    delivery_name_show:false,//收货人提示
    mobile_show:false,//手机号提示
    province_show:false,//省市区提示
    address_show:true,//详细地址提示
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let l_address = app.functions.getLocalStorage('l_address');
    let user = app.functions.getLocalStorage('user');
    if (l_address) {
      this.setData({
        delivery_name: l_address.deliveryName,
        mobile: l_address.mobile,
        province: l_address.province,
        city: l_address.city,
        district: l_address.district,
        area_code: l_address.area_code,
        address: l_address.address,
        lng:l_address.lng,
        lat:l_address.lat,
        xiaoqu: l_address.xiaoqu,
        is_default: l_address.isDefault
      })
      wx.setNavigationBarTitle({
        title: '编辑收货地址'
      })
    } else {
      this.setData({
        delivery_name: user.realname ? user.realname : user.nickname,
        mobile: user.mobile
      })
      let user_address = app.functions.getLocalStorage("user_address");
      if (user_address) {
        this.setData({
          delivery_name: user_address.deliveryName,
          mobile: user_address.mobile,
          province: user_address.province,
          city: user_address.city,
          district: user_address.district,
          area_code: user_address.areaCode,
          address: user_address.address,
          xiaoqu: user_address.xiaoqu,
          is_default: user_address.isDefault
        })
      }
      wx.setNavigationBarTitle({
        title: '新增收货地址'
      })
    }
  },
  // 小区
  getChooseLocation(){
    wx.getSetting({
      success (result) {
        if(result.authSetting['scope.userLocation']==false){
          wx.showModal({
            title: '提示', //提示的标题,
            content: '去授权小程序获取地理位置', //提示的内容,
            showCancel: true, //是否显示取消按钮,
            cancelText: '取消', //取消按钮的文字，默认为取消，最多 4 个字符,
            cancelColor: '#000000', //取消按钮的文字颜色,
            confirmText: '确定', //确定按钮的文字，默认为取消，最多 4 个字符,
            confirmColor: '#3CC51F', //确定按钮的文字颜色,
            success: res => {
              if(res.confirm){
                wx.openSetting({
                  success (res) {
                  }
                })
              }
            }
          });
        }
      }
    })
    var that=this;
    wx.chooseLocation({
        success: function (res) {
          // console.info(res);
          that.setData({
            lng:res.longitude,
            lat:res.latitude,
            xiaoqu:res.name
          })
        },
        fail: function () {
          wx.openSetting({

          })
        },
        complete: function () {
        
        }
    })

  },
  // 名称
  bindNameInput(e) {
    this.setData({
      delivery_name: e.detail.value
    },()=>{
      if(this.data.delivery_name.length>0){
        this.setData({
          delivery_name_show:false
        })
      }else{
        this.setData({
          delivery_name_show:true
        })
      }
    })
  },
  // 联系电话
  bindPhoneInput(e) {
    this.setData({
      mobile: e.detail.value
    },()=>{
      if(this.data.mobile.length>0){
        this.setData({
          mobile_show:false
        })
      }else{
        this.setData({
          mobile_show:true
        })
      }
    })
  },
  // 地址
  bindAddressInput(e) {
    this.setData({
      address: e.detail.value
    })
  },
  // 邮政编码
  bindCodeInput(){
    this.setData({
      area_code: e.detail.value
    })
  },
  trim(str){
    　return str.replace(/(^\s*)|(\s*$)/g, "");
  },
  save() {
    let that = this;
    let user = app.functions.getLocalStorage("user");
    if (app.functions.isEmpty(that.data.delivery_name)) {
      that.setData({
        delivery_name_show:true
      })
      app.functions.showToast('请填写收货人姓名');
      return;
    }
    if (app.functions.mobile(that.data.mobile)==false) {
      that.setData({
        mobile_show:true
      })
      app.functions.showToast('请填写正确手机号码');
      return;
    }
    if (app.functions.isEmpty(that.data.mobile)) {
      that.setData({
        mobile_show:true
      })
      app.functions.showToast('请填写收货人号码');
      return;
    }
    if (app.functions.isEmpty(that.data.province)) {
      that.setData({
        province_show:true
      })
      app.functions.showToast('请选择所在地');
      return;
    }
    if (app.functions.isEmpty(that.trim(that.data.address))){
      app.functions.showToast('请填写收货详细地址');
      return;
    }
    let params = {
      lat: that.data.lat,// 纬度
      lng: that.data.lng,//经度
      mid: user.id,
      deliveryName: that.data.delivery_name,
      mobile: that.data.mobile,
      province: that.data.province,
      city: that.data.city,
      district: that.data.district,
      areaCode: that.data.area_code,
      address: that.data.address,
      xiaoqu: that.data.xiaoqu,
      isDefault: that.data.is_default
    }
    wx.showModal({
      title: '', //提示的标题,
      content: '为确保您的宝贝准确无误的送到您的手里，请确认您的收货地址是否填写完善', //提示的内容,
      showCancel: true, //是否显示取消按钮,
      cancelText: '我再看看', //取消按钮的文字，默认为取消，最多 4 个字符,
      cancelColor: '#878787', //取消按钮的文字颜色,
      confirmText: '已确认', //确定按钮的文字，默认为取消，最多 4 个字符,
      confirmColor: '#5069B4', //确定按钮的文字颜色,
      success: res => {
        if(res.confirm){
          let l_address = app.functions.getLocalStorage('l_address');
          if (l_address) {
            params.id = l_address.id;
            app.api.updateAddressById(params, (response) => {
              app.functions.removeLocalStorage('l_address');
              app.functions.showToast("修改成功!");
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                });
              }, 2000);
            }, (error) => {
              app.functions.showToast(error.msg);
            })
            return false;
          }
          app.api.addAddress(params, (response) => {
            app.functions.removeLocalStorage('l_address');
            app.functions.showToast("保存成功!");
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              });
            }, 2000);
          }, (error) => {
            app.functions.showToast(error.msg);
          })
        }
      }
    });
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.functions.removeLocalStorage('l_address');
    app.functions.removeLocalStorage("user_address");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


  onChangeDefault({ detail }){
    this.setData({ is_default: detail?1:0 });

  },
  popupopen() {
    this.setData({
      show: true
    })
  },
  areaChange(e) {
    this.setData({
      values: e.detail.values
    })
  },
  confirm(e) {
    let values = this.data.values;
    if (values.length > 0) {
      this.setData({
        province: values[0].name,
        city: values[1].name,
        district: values[2].name,
        area_code: values[2].code,
        show: false,
        province_show:false
      })
    }else{
      this.setData({
        province: e.detail.values[0].name,
        city: e.detail.values[1].name,
        district: e.detail.values[2].name,
        area_code: e.detail.values[2].code,
        show: false,
        province_show:false
      })
    }
  },
  cancel() {
    this.setData({
      show: false
    })
  },
  getSubscribeAddress(){
    //用户选择收货地址
    var that = this;
    if (wx.chooseAddress) {
      wx.chooseAddress({
        success: function (res) {
          that.setData({
            delivery_name: res.userName,
            mobile: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            district: res.countyName,
            area_code: res.postalCode,
            address: res.detailInfo
          })
        },
        fail: function (err) {
          app.functions.showToast("发货需要您提供地址");
        }
      })
    } else {
      // console.log('当前微信版本不支持chooseAddress');
    }
  }
})